#!/usr/bin/env python

import config
import picture_source
import processor
import datetime
import time

class Processor:
   def __init__(self, xconfig, cname):
      self.process_list = [ ]
      self.config = xconfig
      self.xclass = cname

      self.__load_process_list()

   def __load_process_list(self):
      for item in self.config['processors#node'].getchildren():
         if item.attrib['class'] == self.xclass:
            processor_name = item.attrib['type']
            self.process_list.append(processor.create(self.config,
                                     processor_name))

   def process_one(self, state):
      data = None
      ts   = datetime.datetime.now()
      for proc in self.process_list:
         (data, ts, state) = proc.process(data, ts, state)

      return state

class TimeLapser:
   def __init__(self, xconfig, processor, archiver):
      self.config = xconfig
      self.processor = processor
      self.archiver = archiver
      self.state = False
      self.done = False
      self.start_time = None
      self.frame_count = 0
      try:
         self.rollup_interval = datetime.timedelta(seconds=self.config.GetInterval('intervals/rollup'))
         self.rollup_count = -1
      except:
         self.rollup_interval = None
         self.rollup_count = int(self.config['intervals/rollup#count']) + 1

   def should_archive(self):
      if self.rollup_count > 0:
         logging.debug("Frame Count: %d" % self.frame_count)
         self.frame_count += 1
         if (self.frame_count < self.rollup_count):
            return False
         else:
            logging.debug("Roll Over")
            self.frame_count = 0
            return True
      if self.start_time == None:
         return False
      if (datetime.datetime.now() - self.start_time) >= self.rollup_interval:
         return True
      else:
         return False

   def run(self):
      self.start_time = datetime.datetime.now()
      while(not self.done):
         if (self.state):
            self.state = self.archiver.process_one(self.state)
            self.start_time = datetime.datetime.now()
            self.state = False
         else:
            self.state = self.processor.process_one(self.state)
            self.state = self.should_archive()

def main(config_file=None):
   tlconf = config.config(config_file)
   processor = Processor(tlconf, 'frame')
   archiver = Processor(tlconf, 'rollup')
   runner = TimeLapser(tlconf, processor, archiver)

   runner.run()

if __name__ == "__main__":
   import sys
   import logging, logging.config

   logging.basicConfig(level=logging.DEBUG)
   try:
      logging.config.fileConfig('logging.ini')
   except:
      pass

   try:
      config_file = sys.argv[1]
   except IndexError:
      config_file = "config.xml"

   main(config_file=config_file)
